package ru.ifmo.croak.impl.ui.query.team1;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ifmo.croak.api.Message;
import ru.ifmo.croak.api.MessageListener;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class MessagesModel implements MessageListener {
    private static final Logger log = LoggerFactory.getLogger(MessagesModel.class);
    JEditorPane jEditorPane;
    Set<UUID> uuids;

    StringBuilder text;
    private final String HEADER = "<html>\n" +
            "   <head>\n" +
            "     <title>Messages</title>\n" +
            "     \n" +
            "   </head>\n" +
            "   <body>\n";
    private final String FOOTER = "   </body>\n" +
            " </html>\n";

    public MessagesModel() {
        uuids = new HashSet<UUID>();
        text = new StringBuilder();
    }

    public void messageAvailable(final Message message) {
        log.trace("message available {}", message);
        if (uuids.add(message.getId())) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    if (jEditorPane != null) {
                        String msg = "<p>" + messageToString(message) + "</p>\n";
                        text.append(msg);
                        jEditorPane.setText(HEADER + text + FOOTER);
                    } else {
                        log.warn("jTextArea == null");
                    }
                }
            });
        }
    }

    static String messageToString(Message message) {
        return "(" + new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US).format(new Date(message.getTime())) + ") <b>" + message.getAuthor() + "</b>: " + message.getText();
    }

    public void setEditorPane(JEditorPane jEditorPane) {
        this.jEditorPane = jEditorPane;
    }
}
